package com.ssamkj.wstar.controller.godMode;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.ssamkj.wstar.dto.godMode.LocaleDTO;
import com.ssamkj.wstar.dto.godMode.RSS_Attr1;
import com.ssamkj.wstar.dto.godMode.RSS_Attr2;
import com.ssamkj.wstar.dto.godMode.RSS_List;
import com.ssamkj.wstar.dto.rss.RssAttrFirstDTO;
import com.ssamkj.wstar.dto.rss.RssAttrSecondDTO;
import com.ssamkj.wstar.service.IGodModeService;

/**
 * Handles requests for the application home page.
 */
@Controller
@RequestMapping(value = "/godMode/")
public class GodModeController {

	@Autowired
	IGodModeService godService;
	
	private static final Logger logger = LoggerFactory
			.getLogger(GodModeController.class);

	

	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public ModelAndView home(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);
		System.out.println("GodMode");

		ModelAndView mav = new ModelAndView("godMain.god");
		mav.addObject("locale", godService.readNationList());
		mav.addObject("attrs", getAttrs());

		
		
		List<RSS_List> list = godService.readRSS_List();
		for(RSS_List r : list){
			System.out.println(r);
		}
		mav.addObject("rss_list", list);
		return mav;
	}

	
	@RequestMapping(value = "/register", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView researchAction(Model model,  HttpServletRequest request, @RequestParam Map<?, ?> paramMap) {
		
//		Iterator i = paramMap.keySet().iterator();
//		while(i.hasNext()){
//			System.out.println(paramMap.get(i.next()).toString());
//		}
//		
//		String json = (String)(paramMap.get("data"));
		RSS_List dto = new RSS_List();
		JSONObject pObj = JSONObject.fromObject(paramMap);
		Iterator<String> it = pObj.keys();
		String key;
		while(it.hasNext()){
			key = it.next();
					
			System.out.println(key+":"+pObj.get(key));
			
		}
		
		dto.setName(pObj.get("name").toString());
		dto.setAttr1(Integer.parseInt(pObj.get("attr1").toString()));
		int attr2 = 0;
		if(!pObj.get("attr2").toString().equals("-")){
			attr2 = Integer.parseInt(pObj.get("attr2").toString());	
		}
		 
		dto.setAttr2(attr2);
		dto.setUrl(pObj.get("url").toString());
		dto.setNation(pObj.get("nation").toString());
		godService.insertRSS(dto);
		model.addAttribute("result", pObj);

		RedirectView rv = new RedirectView("/godMode/");
		rv.setExposeModelAttributes(false);
		return new ModelAndView(rv);
	}
	

	@RequestMapping(value = "/nation", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView nationRegister(Model model,  HttpServletRequest request, @RequestParam Map<?, ?> paramMap) {
		System.out.println("nationRegister");

		ModelAndView mav = new ModelAndView("nation.god");
		mav.addObject("locale", godService.readNationList());

		return mav;
	}
	

	@RequestMapping(value = "/attr1", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView nationAttr1(Model model,  HttpServletRequest request, @RequestParam Map<?, ?> paramMap) {
		System.out.println("nationRegister");

		
		return makeAttr();
	}
	
	
	private ModelAndView makeAttr(){
		ModelAndView mav = new ModelAndView("attr1.god");
		
		List<RssAttrFirstDTO> list = new ArrayList<RssAttrFirstDTO>();
		List<RssAttrSecondDTO> seconds = new ArrayList<RssAttrSecondDTO>();
		
		
		
		List<RSS_Attr1> attr1 = godService.readAttr1List();
		List<RSS_Attr2> attr2 = godService.readAttr2List();
		
		for(RSS_Attr2 a2 : attr2){
			System.out.println(a2);
			RssAttrSecondDTO s = new RssAttrSecondDTO();
			s.setFirstId(a2.getAttr1_id());
			s.setSecondId(a2.getMyid());
			s.setSecondName(a2.getName());
			seconds.add(s);
		}
		
		for(RSS_Attr1 a1 : attr1){
			System.out.println(a1);
			RssAttrFirstDTO f = new RssAttrFirstDTO();
			int myid = a1.getMyid();
			f.setFirstId(myid);
			f.setFirstName(a1.getName());
			List<RssAttrSecondDTO> sec = new ArrayList<RssAttrSecondDTO>();
			for(RssAttrSecondDTO s : seconds){
				if(myid == s.getFirstId()){
					sec.add(s);
				}
			}
			f.setSeconds(sec);
			list.add(f);
		}
		
		mav.addObject("attrs", list);
		
		return mav;
		
	}
	

	@RequestMapping(value = "/attr2", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView nationAttr2(Model model,  HttpServletRequest request, @RequestParam Map<?, ?> paramMap) {
		System.out.println("nationRegister");

		ModelAndView mav = new ModelAndView("attr2.god");
		mav.addObject("locale", godService.readNationList());

		return mav;
	}

	@RequestMapping(value = "/modify", method = { RequestMethod.POST })
	public ModelAndView nationModify(Model model,  HttpServletRequest request, @RequestParam Map<?, ?> paramMap) {
		System.out.println("nationModify");

		ModelAndView mav = new ModelAndView("nation.god");
		mav.addObject("locale", godService.readNationList());

		return mav;
	}
	
	
	
	@RequestMapping(value = "/attr1insert", method = { RequestMethod.POST })
	public ModelAndView nationAttr1insert(Model model,  HttpServletRequest request, @RequestParam Map<?, ?> paramMap) {
		System.out.println("nationModify");

		
		String target = paramMap.get("target").toString();
		if(target.equals("attr1")){
			RSS_Attr1 dto = new RSS_Attr1();
			dto.setName(paramMap.get("firstName").toString());
			
			int myid =1;
			
			List<RSS_Attr1> attr1= godService.readAttr1List();
			if(attr1!=null){
				for(RSS_Attr1 a : attr1){
					myid = a.getMyid()>myid?a.getMyid():myid;
				}
				myid++;
			}
			
			viewMap(paramMap);
			dto.setMyid(myid);
			System.out.println(dto);
			
			godService.insertAttr1(dto);	
		}else{
			RSS_Attr2 dto = new RSS_Attr2();
			dto.setAttr1_id(Integer.parseInt(paramMap.get("firstId").toString()));
			dto.setName(paramMap.get("secondName").toString());
			
			int myid =2;
			
			List<RSS_Attr2> attr2= godService.readAttr2List();
			if(attr2!=null){
				for(RSS_Attr2 a : attr2){
					myid = a.getMyid()>myid?a.getMyid():myid;
				}
				myid++;
			}
			
			viewMap(paramMap);
			dto.setMyid(myid);
			System.out.println(dto);
			
			godService.insertAttr2(dto);	
			
			
		}
		
		return makeAttr();
	}
	
	@RequestMapping(value = "/insert", method = { RequestMethod.POST })
	public ModelAndView nationInsert(Model model,  HttpServletRequest request, @RequestParam Map<?, ?> paramMap) {
		System.out.println("nationModify");

		ModelAndView mav = new ModelAndView("nation.god");
		LocaleDTO dto = new LocaleDTO();
		dto.setName(paramMap.get("name").toString());
		dto.setLoc(paramMap.get("loc").toString());
		viewMap(paramMap);
		System.out.println(dto);
		
		godService.insertNation(dto);
		
		
		mav.addObject("locale", godService.readNationList());

		return mav;
	}
	
	
	public static void viewMap(Map<?, ?> map) {
		
		StringBuilder sb = new StringBuilder();
		sb.append("#####################################################").append("\n");
		Iterator<?> iterator = map.entrySet().iterator();
		while (iterator.hasNext()) {
			Map.Entry<String, String> pairs = extracted(iterator);
				sb.append("----------------------------------\n");
				sb.append("key : " + pairs.getKey() + ", value : "
						+ pairs.getValue()).append("\n");
				sb.append("----------------------------------").append("\n");
		}
		sb.append("#####################################################").append("\n");
		System.out.println(sb.toString());
	}
	
	public static Entry<String, String> extracted(Iterator<?> iterator) {
		return (Map.Entry<String, String>) iterator.next();
	}
	
	
	
	
	private List<RssAttrFirstDTO> getAttrs() {
		List<RssAttrFirstDTO> list = new ArrayList<RssAttrFirstDTO>();
		List<RssAttrSecondDTO> seconds = new ArrayList<RssAttrSecondDTO>();
		
		List<RSS_Attr1> attr1 = godService.readAttr1List();
		List<RSS_Attr2> attr2 = godService.readAttr2List();
		
		for(RSS_Attr2 a2 : attr2){
//			System.out.println(a2);
			RssAttrSecondDTO s = new RssAttrSecondDTO();
			s.setFirstId(a2.getAttr1_id());
			s.setSecondId(a2.getMyid());
			s.setSecondName(a2.getName());
			seconds.add(s);
		}
		
		for(RSS_Attr1 a1 : attr1){
//			System.out.println(a1);
			RssAttrFirstDTO f = new RssAttrFirstDTO();
			int myid = a1.getMyid();
			f.setFirstId(myid);
			f.setFirstName(a1.getName());
			List<RssAttrSecondDTO> sec = new ArrayList<RssAttrSecondDTO>();
			for(RssAttrSecondDTO s : seconds){
				if(myid == s.getFirstId()){
					sec.add(s);
				}
			}
			f.setSeconds(sec);
			list.add(f);
		}

		return list;
	}


}
